package com.os.opencv.java.chapter9;

import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

public class ContourHierarchy {

    public static void main(String[] args) {

        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        //读取图像并在屏幕上显示
        Mat src = Imgcodecs.imread("/Users/matt/Pictures/111.jpg", Imgcodecs.IMREAD_GRAYSCALE);
        HighGui.imshow("wanlifuwangshi", src);
        HighGui.waitKey(0);

        Mat binary = new Mat();
        Imgproc.threshold(src, binary, 90, 255, Imgproc.THRESH_BINARY);
        HighGui.imshow("binary", binary);
        HighGui.waitKey(0);

        //根据而知图检测轮廓
        List<MatOfPoint> contour = new ArrayList<>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(binary, contour, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);

        //画出轮廓并在屏幕上显示
        Mat imgCanny = new Mat(src.height(), src.width(), CvType.CV_8UC3, new Scalar(255,255,255));
        for(int i=0; i<contour.size(); i++) {
            Imgproc.drawContours(imgCanny, contour, i, new Scalar(0, 0, 0), 1);
        }
        HighGui.imshow("contours", imgCanny);
        HighGui.waitKey(0);

        //在控制台显示hierarchy层级数据
        for(int i=0; i<contour.size(); i++){
            double[] d = hierarchy.get(0, i);
            for(int j=0; j<d.length; j++){
                System.out.println(d[j] + ",");
            }
            System.out.println();
        }
        System.exit(0);
    }
}
